<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      #box {
        display: flex;
        width: 400px;
        height: 400px;

        margin: 100px 0 0 200px;
        display: flex;
        justify-content: center;
        align-items: center;
        border: solid;
        font-size: 40px;
        position: relative;
      }
      #box div {
        width: 100px;
        height: 100px;
        background-color: beige;
        display: flex;
        align-items: center;
        justify-content: center;
        border: solid;
        cursor: pointer;
        position: absolute;
      }
    </style>
  </head>
  <body>
    <div id="box">
      <div data-ball>1</div>
    </div>
    <script>
      const { x: boxX, y: boxY } = document
        .getElementById("box")
        .getBoundingClientRect();
      document.onmousedown = function (e) {
        const ball = e.target.dataset.ball;
        if (ball === undefined) return;
        e.target.style.cursor = "all-scroll";

        //----

        const { x: targetX, y: targetY } = e.target.getBoundingClientRect();

        document.onmousemove = (e1) => {
          e.target.style.top = e1.clientY - boxY - (e.clientY - targetY) + "px";
          e.target.style.left =
            e1.clientX - boxX - (e.clientX - targetX) + "px";
        };
      };

      document.onmouseup = (e) => {
        e.target.style.cursor = "";
        document.onmousemove = null;
      };
    </script>
  </body>
</html>
